package com.ruoyi.jiaopei.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.jiaopei.domain.TbCurriculumStudent;
import com.ruoyi.jiaopei.domain.TbUserStudent;
import com.ruoyi.jiaopei.domain.bo.TbUserStudentBo;
import com.ruoyi.jiaopei.domain.vo.StudentCurriculumVo;
import com.ruoyi.jiaopei.service.ITbCurriculumStudentService;
import com.ruoyi.jiaopei.service.ITbUserStudentService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.jiaopei.domain.bo.TbStudentBo;
import com.ruoyi.jiaopei.domain.vo.TbStudentVo;
import com.ruoyi.jiaopei.domain.TbStudent;
import com.ruoyi.jiaopei.mapper.TbStudentMapper;
import com.ruoyi.jiaopei.service.ITbStudentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
/**
 * 学员Service业务层处理
 *
 * @author macy
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class TbStudentServiceImpl implements ITbStudentService {

    private final TbStudentMapper baseMapper;
    private final ISysUserService sysUserService;
    private final ITbCurriculumStudentService curriculumStudentService;
    private final ITbUserStudentService userStudentService;


    /**
     * 查询学员
     */
    @Override
    public TbStudentVo queryById(Long id){
        TbStudentVo studentVo=baseMapper.selectVoById(id);
        if(null!=studentVo){

            if(null!=studentVo.getTeacherId()){
                studentVo.setTeacherVo(sysUserService.selectUserById(studentVo.getTeacherId()));
            }

            if(null!=studentVo.getSalesId()){
                studentVo.setSalesVo(sysUserService.selectUserById(studentVo.getSalesId()));
            }
        }
        return studentVo;
    }


    /**
     * 查询 学员课程
     */
    @Override
    public TableDataInfo<StudentCurriculumVo> queryStudentCurriculum(TbStudentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbStudent> lqw = buildQueryWrapper1(bo);

        Page<StudentCurriculumVo> result = baseMapper.queryStudentCurriculum(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    @Override
    public TableDataInfo<StudentCurriculumVo> queryStudentCurriculumNew(TbStudentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbStudent> lqw = buildQueryWrapper1(bo);

        Page<StudentCurriculumVo> result = baseMapper.queryStudentCurriculumNew(pageQuery.build(),bo,lqw);
        return TableDataInfo.build(result);
    }


    @Override
    public StudentCurriculumVo queryStudentCurriculumInfo(TbStudentBo bo) {
        LambdaQueryWrapper<TbStudent> lqw = buildQueryWrapper1(bo);
        return baseMapper.queryStudentCurriculumInfo(lqw);
    }

    @Override
    public StudentCurriculumVo queryStudentCurriculumInfo(Wrapper<TbStudent> queryWrapper) {
        return baseMapper.queryStudentCurriculumInfo(queryWrapper);
    }

    /**
     * 查询学员列表
     */
    @Override
    public TableDataInfo<TbStudentVo> queryPageList(TbStudentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbStudent> lqw = buildQueryWrapper(bo);
        Page<TbStudentVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }



    /**
     * 查询学员列表
     */
    @Override
    public List<TbStudentVo> queryList(TbStudentBo bo) {
        LambdaQueryWrapper<TbStudent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbStudent> buildQueryWrapper(TbStudentBo bo) {

        QueryWrapper<TbStudent> lqw1 = Wrappers.query();
        lqw1.like(StrUtil.isNotEmpty(bo.getTeacherName()),"u.nick_name",bo.getTeacherName());
        lqw1.like(StrUtil.isNotEmpty(bo.getSalesName()),"u1.nick_name",bo.getSalesName());
        lqw1.apply(null!=bo.getCurriculumId()," t.id in(SELECT s.student_id FROM tb_curriculum_student s where s.curriculum_id={0} )",bo.getCurriculumId());
        lqw1.apply(null!=bo.getClassId()," t.id not IN ( SELECT s.student_id FROM tb_class_student s WHERE s.class_id ={0} )",bo.getClassId());

        LambdaQueryWrapper<TbStudent> lqw = lqw1.lambda();

        lqw.like(null!=bo.getTeacherId(), TbStudent::getTeacherId, bo.getTeacherId());
        lqw.like(null!=bo.getSalesId(), TbStudent::getSalesId, bo.getSalesId());

        lqw.like(StringUtils.isNotBlank(bo.getName()), TbStudent::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getTel()), TbStudent::getTel, bo.getTel());
        lqw.like(StringUtils.isNotBlank(bo.getParents()), TbStudent::getParents, bo.getParents());
        lqw.like(StringUtils.isNotBlank(bo.getParentsTel()), TbStudent::getParentsTel, bo.getParentsTel());
        lqw.like(StringUtils.isNotBlank(bo.getAddress()), TbStudent::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getIntention()), TbStudent::getIntention, bo.getIntention());
        return lqw;
    }

    private LambdaQueryWrapper<TbStudent> buildQueryWrapper1(TbStudentBo bo) {

        QueryWrapper<TbStudent> lqw1 = Wrappers.query();
        lqw1.like(StrUtil.isNotEmpty(bo.getName()),"t.name",bo.getName());
        lqw1.like(StrUtil.isNotEmpty(bo.getCurriculumName()),"a.curriculum_name",bo.getCurriculumName());
        lqw1.like(StrUtil.isNotEmpty(bo.getTeacherName()),"s.nick_name",bo.getTeacherName());
        lqw1.like(StrUtil.isNotEmpty(bo.getSalesName()),"u.nick_name",bo.getSalesName());

        lqw1.eq(null!=bo.getCurriculumId(),"a.curriculum_id",bo.getCurriculumId());
        lqw1.eq(null!=bo.getTeacherId(),"t.teacher_id",bo.getTeacherId());
        lqw1.eq(null!=bo.getSalesId(),"t.sales_id",bo.getSalesId());

        lqw1.eq(null!=bo.getId(),"t.id",bo.getId());

        lqw1.orderByAsc("sy_hours");

        LambdaQueryWrapper<TbStudent> lqw = lqw1.lambda();


        return lqw;
    }

    /**
     * 新增学员
     */
    @Transactional
    @Override
    public Boolean insertByBo(TbStudentBo bo) {
        TbStudent add = BeanUtil.toBean(bo, TbStudent.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        validEntityAfterSave(bo,add,true);
        return flag;
    }

    /**
     * 修改学员
     */
    @Override
    public Boolean updateByBo(TbStudentBo bo) {
        TbStudent update = BeanUtil.toBean(bo, TbStudent.class);
        validEntityBeforeSave(update);
        boolean flg=baseMapper.updateById(update) > 0;

        //validEntityAfterSave(bo,update,false);

        return flg;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbStudent entity){

        if(null!=entity.getParentsTel()&&entity.getParentsTel().length()!=11){
            throw new ServiceException("家长手机号格式不正确");
        }

        if(null==entity.getId()){
            entity.setCreatedDate(new Date());
            if(null==entity.getTeacherId()){
                entity.setTeacherId(LoginHelper.getUserId());
            }
            if(null==entity.getSalesId()){
                entity.setSalesId(LoginHelper.getUserId());
            }
        }else{
            TbStudentVo vo=baseMapper.selectVoById(entity.getId());
            if(null!=vo){
                /**
                 * 新手机号
                 */
                String parentsTel=entity.getParentsTel();
                /**
                 * 老 手机号
                 */
                String dbParentsTel=vo.getParentsTel();


                /**
                 * 新旧 手机号 都不为空的时候
                 */
                if(StrUtil.isNotBlank(parentsTel)&&StrUtil.isNotBlank(dbParentsTel)&&!dbParentsTel.equals(parentsTel)){

                    SysUser sysUser=sysUserService.selectUserByUserName(parentsTel);
                    if(null!=sysUser){
                        userStudentService.update(new LambdaUpdateWrapper<TbUserStudent>()
                            .eq(TbUserStudent::getStudentId,vo.getId())
                            .set(TbUserStudent::getUserId,sysUser.getUserId())
                        );
                    }else{
                        sysUser=sysUserService.selectUserByUserName(dbParentsTel);
                        if(null!=sysUser){
                            sysUserService.update(new LambdaUpdateWrapper<SysUser>()
                                .eq(SysUser::getUserId,sysUser.getUserId())
                                .set(SysUser::getUserName,parentsTel)
                                .set(SysUser::getPhonenumber,parentsTel)
                                .set(SysUser::getNickName,entity.getParents())
                            );
                        }
                    }

                    /**
                     * 同步其他学员的手机号
                     */
                    baseMapper.update(new LambdaUpdateWrapper<TbStudent>()
                        .eq(TbStudent::getParentsTel,dbParentsTel)
                        .set(TbStudent::getParentsTel,parentsTel)
                    );
                }
            }
        }
    }
    /**
     * 保存后的数据校验
     */
    private void validEntityAfterSave(TbStudentBo tbStudentBo,TbStudent entity,Boolean isAdd){
        /**
         * 使用家长电话 自动创建账号
         */
        if(isAdd&&StrUtil.isNotBlank(entity.getParentsTel())){

            SysUser user=new SysUser();
            user.setNickName(entity.getParents());
            user.setUserName(entity.getParentsTel());
            user.setPhonenumber(entity.getParentsTel());
            user.setPassword(BCrypt.hashpw("123456"));
            user.setTeacher("3");

            if (sysUserService.checkUserNameUnique(user)) {
                int i=sysUserService.insertUser(user);
                if(i>0){
                    userStudentService.insertByBo(new TbUserStudentBo(user.getUserId(),entity.getId()));
                }
            }else{
                user=sysUserService.selectUserByUserName(entity.getParentsTel());
                if(null!=user){
                    userStudentService.insertByBo(new TbUserStudentBo(user.getUserId(),entity.getId()));
                }
            }


            /*** 添加学员的时候 可以顺便 添加课时 ****/
            if(null!=tbStudentBo.getCurriculumStudentBo()){
                tbStudentBo.getCurriculumStudentBo().setStudentId(entity.getId());
                if(null==tbStudentBo.getCurriculumStudentBo().getSalesId()){
                    tbStudentBo.getCurriculumStudentBo().setSalesId(entity.getSalesId());
                }
                curriculumStudentService.insertByBo(tbStudentBo.getCurriculumStudentBo());
            }


        }


    }

    /**
     * 批量删除学员
     */
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if(isValid){
            for (int i = 0; i <ids.size() ; i++) {
                long count=curriculumStudentService.selectCount(new LambdaQueryWrapper<TbCurriculumStudent>()
                    .eq(TbCurriculumStudent::getStudentId,ids.get(i))
                );

                if(count>0){
                    throw new ServiceException("学员名下还有关联课程，不能删除。");
                }

            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    public int update(Wrapper<TbStudent> updateWrapper){
       return baseMapper.update(updateWrapper);
    }


}
